package douyin

import (
	"GoServer/utils/config"
	"GoServer/utils/debug"
	"GoServer/utils/tool"
	"encoding/json"
	"errors"
)

type RoomInfo struct {
	ErrorCode    int    `json:"error_code"`
	ErrorMsg     string `json:"error_msg"`
	RoomId       int64  `json:"room_id"`
	AnchorOpenId string `json:"anchor_open_id"`
	AvatarURL    string `json:"avatar_url"`
	NickName     string `json:"nick_name"`
}

type RequstRoomResponseError struct {
	ErrorCode    int    `json:"errcode"`
	ErrorMessage string `json:"errmsg"`
}

type RequestRoomInfo struct {
	Token string `json:"token"`
}

type RequestRoomInfoResponse struct {
	Data Data `json:"data"`
}

type Data struct {
	Info Info `json:"info"`
}

type Info struct {
	AnchorOpenID string `json:"anchor_open_id"`
	AvatarURL    string `json:"avatar_url"`
	NickName     string `json:"nick_name"`
	RoomID       int64  `json:"room_id"`
}

// /请求房间id
func RequestRoomID(clientToken string, gameName string) ([]byte, error) {
	defer func() {
		if r := recover(); !tool.InterfaceIsNil(r) {
			debug.Logf(debug.Error, "请求房间id错误，直接返回给客户端")
		}
	}()

	debug.Logln(debug.Info, "请求直播间房间id")

	data := &RequestRoomInfo{
		Token: clientToken,
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		return nil, errors.New("Request Room json.Marshal err:" + err.Error())
	}
	jsonStr := string(reqBody)
	debug.Logln(debug.Info, "请求房间信息json: ", jsonStr)

	headers := map[string]string{
		"X-Token":      GetDYAccessToken(gameName),
		"Content-Type": "application/json;",
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.requestRoomId"), jsonStr, headers)
	if err != nil {
		return nil, errors.New("Request Room httpPost err:" + err.Error())
	}

	msg := RequestRoomInfoResponse{}
	result := RoomInfo{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Warn, "请求房间信息失败， 解析失败原因")
		errMsg := RequstRoomResponseError{}
		if err := json.Unmarshal(res, &errMsg); err != nil {
			debug.Logln(debug.Warn, "失败原因解析失败，直接返回客户端")
			return nil, errors.New("解析失败")
		}

		///返回失败原因
		result.ErrorCode = errMsg.ErrorCode
		result.ErrorMsg = errMsg.ErrorMessage
	} else {
		result.ErrorCode = 0
		result.RoomId = msg.Data.Info.RoomID
		result.AnchorOpenId = msg.Data.Info.AnchorOpenID
		result.NickName = msg.Data.Info.NickName
		result.AvatarURL = msg.Data.Info.AvatarURL
	}

	resultBytes, _ := json.Marshal(result)
	return resultBytes, nil
}
